package com.hcb.webservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class WebService {
	
	private static WebService instance;

	public static WebService getInstance(){
		if(instance == null)
			instance = new WebService();
		return instance;
	}
	
	/**
	 * For UpdateData: 	UpdateData/tblname/user/type/1/username/p/password/abc/phone/123/country/vn
	 * For GetData: 	GetData/service/get_log/change_log_id/0
	 * @param path
	 * @return
	 */
	public String get(String path){
		try {
			 
			DefaultHttpClient httpClient = new DefaultHttpClient();
			String urlPath = path;
			HttpGet getRequest = new HttpGet(urlPath);
			getRequest.addHeader("accept", "application/json");
	 
			HttpResponse response = null;
			try {
				response = httpClient.execute(getRequest);
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			
	 
			if (response.getStatusLine().getStatusCode() != 200) {
				return null;
//				throw new RuntimeException("Failed : HTTP error code : "
//				   + response.getStatusLine().getStatusCode());
			}
	 
			BufferedReader br = new BufferedReader(
	                         new InputStreamReader((response.getEntity().getContent())));
	 
			String output;
			System.out.println("Output from Server .... \n");
			StringBuilder builder = new StringBuilder();
			while ((output = br.readLine()) != null) {
				System.out.println(output);
				builder.append(output);
			}
	 
			httpClient.getConnectionManager().shutdown();
			
			return builder.toString();
	 
		  } catch (ClientProtocolException e) {
	 
			e.printStackTrace();
	 
		  } catch (IOException e) {
	 
			e.printStackTrace();
		  }
		
		return null;
	}

}
